<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.hsycms.com All rights reserved.
// | Author: 神夜 <564379992@qq.com>
// +----------------------------------------------------------------------
error_reporting(E_ERROR | E_PARSE );
use sy\ChinesePinyin;
use PHPMailer\PHPMailer\PHPMailer;

//打印函数
function p($arr){
	echo '<pre>';
	print_r($arr);
	echo '</pre>';	
}

//打印SQL
function printsql($table){
	echo db($table)->getLastSql();
}


//状态
function _status($v){
	if($v==1){
		return '<font color="#00CC99">正常</font>';
	}else{
		return '锁定';
	}
}


//生成缩略图
function _thumb($data){
	$data['thumbwidth'] = $data['thumbwidth'] ? $data['thumbwidth'] : '300';
	$data['thumbheight'] = $data['thumbheight'] ? $data['thumbheight'] : '250';
	$namearr = explode('/',$data['img']);
	$imgname = strstr($namearr[3],'_');	 
	if($imgname!=""){ $namearr[3] = substr($imgname,1);	}
	$thumbname = $data['thumbwidth'].'x'.$data['thumbheight'].'_'.$namearr[3];
	$thumb = '/upload/'.$namearr[2].'/'.$thumbname; 	
	$thumburl = ROOT_PATH . DS . 'upload/'.$namearr[2].'/'.$thumbname;   
	$image = \think\Image::open('.'.$data['img']);
	$image->thumb($data['thumbwidth'],$data['thumbheight'],\think\Image::THUMB_FIXED)->save($thumburl);
	return $thumb;	
}

//获取原图
function _getbigimg($img){
	$namearr = explode('/',$img);
	$imgname = strstr($namearr[3],'_');	 
	if($imgname!=""){ 
	  $namearr[3] = substr($imgname,1);
	  return '/upload/'.$namearr[2].'/'.$namearr[3];		 	
	}else{
	  return $img;	 
	}
}

//属性管理
function _attr($v,$attr){
	if($attr=='ishome' && $v==1){
		return '<font color="#33FFCC">首页</font>';
	}
	if($attr=='isvouch' && $v==1){
		return '<font color="#0099FF">推荐</font>';
	}
	if($attr=='istop' && $v==1){
		return '<font color="#FF9966">置顶</font>';
	}
}

//时间处理
function inputDate($date){
	$datetime = '';
	if($date!=""){
		$datetime = strtotime($date);
	}else{
		$datetime = time();
	}
	return $datetime;
}

//获取分类名
function getCateName($cid,$nid){
	if($cid==""){
		return db('nav')->where('id',$nid)->value('title');
	}else{
		return db('cate')->where('id',$cid)->value('title');
	}
}

//获取文章数量
function getArticleCount($id){
	return db('article')->where('nid',$id)->count();
}

//获取栏目名
function getNavName($nid){
	return db('nav')->where('id',$nid)->value('title');
}

//获取英文名称
function getEntitle($id){
	$nid = db('article')->where('id='.$id)->value('nid');
	return db('nav')->where('id',$nid)->value('entitle');
}

//获取回复内容
function replyContent($id){
	return db('book2_reply')->where('bid',$id)->value('content');
}


//传入表名查询三级内容后台
function treelist($table,$field="*",$where,$num){
	$where['pid'] = 0;
	$list = db($table)->field($field)->where($where)->order("sort,id")->limit($num)->select();		
	if($list){foreach($list as $key=>$v){
		$list[$key]['son'] = db($table)->field($field)->where('pid',$v['id'])->order("sort,id")->select();		
		if($list[$key]['son'])foreach($list[$key]['son'] as $key1=>$v1){
			$list[$key]['son'][$key1]['son'] = db($table)->field($field)->where('pid',$v1['id'])->order("sort,id")->select();
		}
	}}
	return $list;
}

//传入表名查询三级内容前端
function webtreelist($table,$field="*",$where,$num){
	$where['pid'] = 0;
	if($table=="cate"){ $where['isshow']=1; }
	$list = db($table)->field($field)->where($where)->order("sort,id")->limit($num)->select();		
	if($list){foreach($list as $key=>$v){
		$list[$key]['son'] = db($table)->field($field)->where('pid',$v['id'])->order("sort,id")->select();		
		if($list[$key]['son'])foreach($list[$key]['son'] as $key1=>$v1){
			$list[$key]['son'][$key1]['son'] = db($table)->field($field)->where('pid',$v1['id'])->order("sort,id")->select();
		}
	}}
	return $list;
}

//三级分类查询语句生成
function treecatewhere($cid=0){
	$catecid = array($cid);	//加入本分类	
	$where = '';		
	$sonid = db('cate')->where('pid',$cid)->field('id')->select();		
	if($sonid){
		foreach($sonid as $key=>$v){					
			  $catecid[] .= $v['id'];	//加入本分类
			  foreach($sonid as $key1=>$v1){					 
				 $son2id = db('cate')->where('pid',$v1['id'])->field('id')->select();	
				 if($son2id){
					foreach($son2id as $key2=>$v2){
						 $catecid[] .= $v2['id'];	//加入本分类
					}
				 }
			  }		
		}
		$catecid = array_flip(array_flip($catecid));  //去除数组中重复元素			
		$catecid=implode(',',$catecid);	//拆分分类ID	
		$where .= "$catecid";													
	}else{
		$where .= "$cid";				
	}		
	return $where;
}


//传入数组显示无限级分类
function treearr($arr,$id,$level){
    $list =array();
    foreach ($arr as $k=>$v){
        if ($v['pid'] == $id){
            $v['level']=$level;
            $v['son'] = treearr($arr,$v['id'],$level+1);
            $list[] = $v;
        }
    }
    return $list;
}

//检测英文名称是否存在
/*
* @param $title 标题 $entitle 英文名称  $id 文章ID
*/
function checkEntitle($title,$entitle,$id){
	if($entitle==""){
		$Pinyin = new ChinesePinyin();
		$entitle = $Pinyin->TransformWithoutTone($title);
	}
	$result = $entitle;
	if($entitle != ""){
		if($id==''){
		   $res = db('nav')->where('entitle',$entitle)->find();	
		   $res2 = db('cate')->where('entitle',$entitle)->find();
		   if(!empty($res) || !empty($res2)){
			  $result = "no";	 
		   }
		}else{
			$where['entitle'] = $entitle;
			$where['id'] = array('neq',$id);
			$res  = db('nav')->where($where)->find();
			$res2 = db('cate')->where($where)->find();		
			if(!empty($res) || !empty($res2)){
				 $result = "no";
			}
		}
	}	
	return $result;		
}


//截取字符串
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=false){
	 if(function_exists("mb_substr")){
	  if($suffix)
	   return mb_substr($str, $start, $length, $charset)."...";
	  else
	   return mb_substr($str, $start, $length, $charset);
	 }elseif(function_exists('iconv_substr')) {
	  if($suffix)
	   return iconv_substr($str,$start,$length,$charset)."...";
	  else
	   return iconv_substr($str,$start,$length,$charset);
	 }
	 $re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
	 $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
	 $re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
	 $re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
	 preg_match_all($re[$charset], $str, $match);
	 $slice = join("",array_slice($match[0], $start, $length));
	 if($suffix) return $slice."…";
	 return $slice;
}

//二维数组去掉重复值
function array_unique_fb($array2D){
    foreach ($array2D as $v)
    {
        $v = join(",",$v);  //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
        $temp[] = $v;
    }
    
    $temp = array_unique($temp);   //去掉重复的字符串,也就是重复的一维数组
    foreach ($temp as $k => $v)
    {
        $temp[$k] = explode(",",$v);  //再将拆开的数组重新组装
    }
    return $temp;
}

//发邮件
function sendemail($data){
   $site = db('site')->where('id=1')->find();
   $mail = new PHPMailer();
	  try{
		  //邮件调试模式
		  $mail->SMTPDebug = 0;  
		  //设置邮件使用SMTP
		  $mail->isSMTP();
		  // 设置邮件程序以使用SMTP
		  $mail->Host = $site['email_host'];
		  // 设置邮件内容的编码
		  $mail->CharSet='UTF-8';
		  // 启用SMTP验证
		  $mail->SMTPAuth = true;
		  // SMTP username
		  $mail->Username = $site['email_send_name'];
		  // SMTP password
		  $mail->Password = $site['email_send_pass'];
		  // 启用TLS加密，`ssl`也被接受
		  //$mail->SMTPSecure = 'tls';
		  if($site['email_smtpsecure']!=""){
		  	$mail->SMTPSecure = $site['email_smtpsecure'];
		  }
		  // 连接的TCP端口
		  $mail->Port = $site['email_port'];
		  //设置发件人
		  $mail->setFrom($site['email_send_name'], $site['webtitle']);
		  //网站管理后台添加收件人1
		  $mail->addAddress($site['email_form'], $site['email_form_name']);     // Add a recipient
		  //$mail->addAddress('ellen@example.com');               // Name is optional
		  //收件人回复的邮箱
		  $mail->addReplyTo($data['email'], $data['name']); //网页端客户的邮箱地址，客户的姓名字
		  //抄送
		  //$mail->addCC('cc@example.com');
		  //$mail->addBCC('bcc@example.com');
		  //附件
		  //$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
		  //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
		  //Content
		  // 将电子邮件格式设置为HTML
		  $mail->isHTML(true);
		  $mail->Subject = $data['title'];
		  $mail->Body    = $data['content'];
		  //$mail->AltBody = '这是非HTML邮件客户端的纯文本';
		  $mail->send();
		  //echo 'Message has been sent';
		  //$mail->isSMTP();
	  }catch (Exception $e){
		  echo 'Mailer Error: ' . $mail->ErrorInfo;
	  }
} 

//导航
function nav(){
	$list = db('nav')->where('isshow=1')->field('showcate,id,title,entitle')->order('sort,id')->select();
	if($list){
		foreach($list as $key=>$v){				
			$list[$key]['link'] = '/'.$v['entitle'].'.html';				
			if($v['showcate']==1){
				$list[$key]['son'] = db('cate')->where("nid=".$v['id']." and isshow=1 and pid=0")->field('id,title,entitle')->order("sort,id")->select();
				if($list[$key]['son'])foreach($list[$key]['son'] as $key1=>$v1){						
					$list[$key]['son'][$key1]['link'] = '/'.$v1['entitle'].'.html';
				}
			}else{
				$list[$key]['son'] = db('article')->where("nid=".$v['id'])->field('title,id')->order("sort,id")->select();
				if($list[$key]['son'])foreach($list[$key]['son'] as $key2=>$v2){
					$list[$key]['son'][$key2]['link'] = '/'.$v['entitle'].'/'.$v2['id'].'.html';
				}
			}
		}
	}
	return $list;		
}


function create_item($data){
    $item="<url>\n";
    $item.="<loc>".$data['loc']."</loc>\n";
    $item.="<priority>".$data['priority']."</priority>\n";
    $item.="<lastmod>".$data['lastmod']."</lastmod>\n";
    $item.="<changefreq>".$data['changefreq']."</changefreq>\n";
    $item.="</url>\n";
    return $item;
}

//生成XML 
function makeXML($data_array){
   $content='<?xml version="1.0" encoding="UTF-8"?>
   <urlset
    xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
    http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
   ';  
   foreach($data_array as $data){
    $content.= create_item($data);
   }
   $content.='</urlset>';
   $fp=fopen('sitemap.xml','w+');
   fwrite($fp,$content);
   fclose($fp);
}


//生成站点地图
function sitemap(){
	$url = db('site')->where('id=1')->value('weburl');			
	//默认
	echo '<div style="width:500px; margin:0 auto; background:#fff; border:1px solid #ddd; padding:20px; line-height:22px; font-size:12px; color:red;">';
	$data_array=array(
		array(
		 'loc'=>$url,
		 'priority'=>'1.0',
		 'lastmod'=>date('Y-m-d H:i:s'),
		 'changefreq'=>'always',
		),
		array(
		 'loc'=>$url.'index.html',
		 'priority'=>'1.0',
		 'lastmod'=>date('Y-m-d H:i:s'),
		 'changefreq'=>'always',
		)
	);			
	//导航
	$nav = nav();
	$a = array();
	if($nav){
		foreach($nav as $key=>$v){
			$a[$key] = array(	
				'loc' 		 => $url.$v['entitle'].'.html',
				'priority'   => '1.0',
				'lastmod'	 => date('Y-m-d H:i:s'),
				'changefreq' => 'always',	
			);	
			echo '生成导航'.$url.$v['entitle'].'.html'.'<br/>';
		}
		$data_array= array_merge($data_array,$a);
	}	
	//分类
	$cate = db('cate')->field("entitle")->where("nid != 5")->order("nid,sort,id")->select();
	$b = array();
	if($cate){
		foreach($cate as $key=>$v){
			$b[$key] = array(	
				'loc' 		 => $url.$v['entitle'].'.html',
				'priority'   => '1.0',
				'lastmod'	 => date('Y-m-d H:i:s'),
				'changefreq' => 'always',	
			);	
			echo '生成分类'.$url.$v['entitle'].'.html'.'<br/>';
		}
		$data_array= array_merge($data_array,$b);
	}			
	//文章
	$list = db('article')->field("id,nid,datetime")->where("nid != 5")->order("nid,istop,sort,id")->select();
	$c = array();
	if($list){
		foreach($list as $key=>$v){
			$entitle = db('nav')->where('id',$v['nid'])->value("entitle");
			$c[$key] = array(	
				'loc' 		 => $url.$entitle.'/'.$v['id'].'.html',
				'priority'   => '0.5',
				'lastmod'	 => date('Y-m-d H:i:s',$v['datetime']),
				'changefreq' => 'daily',	
			);	
			echo '生成文章'.$url.$entitle.'/'.$v['id'].'.html'.'<br/>';			
		}
		echo '</div>';
		$data_array= array_merge($data_array,$c);
	}
	makeXML($data_array);
}
	
//百度主动推送
function baiduPushUrl($id,$nid){	
	$site = db('site')->field('weburl,webzdts,webzdtsurl')->where('id=1')->find();	
	if($site['webzdts']==1){
		$api = $site['webzdtsurl'];
		$entitle = db('nav')->where('id',$nid)->value('entitle');				
		$urls = array( $site['weburl'].$entitle.'/'.$id.'.html' );		
		$ch = curl_init();
		$options =  array(
			CURLOPT_URL => $api,
			CURLOPT_POST => true,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_POSTFIELDS => implode("\n", $urls),
			CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
		);
		curl_setopt_array($ch, $options);
		$result = curl_exec($ch);
		return $result;
	}
}

//获取蜘蛛爬虫痕迹
function spider(){
	$ax_ym  = $_SERVER['REQUEST_URI'];
	$ax_ss  = $_SERVER['HTTP_USER_AGENT'];
	$ax_url = $_SERVER['HTTP_REFERER'];
	$ax_ip  = $_SERVER['HTTP_X_FORWARDED_FOR'];
	if(empty($ax_ip)){
		$ax_ip = $_SERVER['REMOTE_ADDR'];
	}	
	$baidu=stristr($ax_ss,"Baiduspider");
	$google=stristr($ax_ss,"Googlebot");
	$soso=stristr($ax_ss,"Sosospider");
	$youdao=stristr($ax_ss,"YoudaoBot");
	$bing=stristr($ax_ss,"bingbot");
	$sogou=stristr($ax_ss,"Sogou web spider");
	$yahoo=stristr($ax_ss,"Yahoo! Slurp");
	$Alexa=stristr($ax_ss,"Alexa");
	$so=stristr($ax_ss,"360Spider");
	if($baidu)
	{
		$ax_ss="baidu";
	}
	elseif($google)
	{
		$ax_ss="Google";
	}
	elseif($soso)
	{
		$ax_ss="soso";
	}
	elseif($youdao)
	{
		$ax_ss="youdao";
	}
	elseif($bing)
	{
		$ax_ss="bing";
	}
	elseif($sogou)
	{
		$ax_ss="sogou";
	}
	elseif($yahoo)
	{
		$ax_ss="yahoo";
	}
	elseif($Alexa)
	{
		$ax_ss="Alexa";
	}
	elseif($so)
	{
		$ax_ss="so";
	}
	else
	{
		$ax_ss=null;
	}
	$data['title']    = $ax_ss;	
	$data['url']      = $ax_ym;
	$data['oldurl']   = $ax_url;
	$data['ip']       = $ax_ip;
	$data['datetime'] = time();
	if($baidu or $google or $soso or $youdao or $bing or $sogou or $yahoo or $Alexa or $so)
	{
		$res = db('spider')->insert($data);
	}
}

//网站内链转换
function siteLinkReplace($arr,$type,$oldarr){
	if($arr){
	  $str='<a href="'.$arr['url'].'" target="_blank" title="'.$arr['title'].'">'.$arr['title'].'</a>';	
	  if($type=='edit'){
	  	$oldstr = '<a href="'.$oldarr['url'].'" target="_blank" title="'.$oldarr['title'].'">'.$oldarr['title'].'</a>';	
	  }else{
	  	$oldstr = $arr['title'];
	  }
	  $list = db('article')->field('id,content')->select();
	  if($list)
	  foreach($list as $key=>$vo){		
		$data['content'] = str_replace($oldstr,$str,$vo['content']);		
		db('article')->where('id',$vo['id'])->update($data);
	  }
    }
}

//删除网站内链
function delSiteLink($arr){
	$str='<a href="'.$arr['url'].'" target="_blank" title="'.$arr['title'].'">'.$arr['title'].'</a>';
	$list = db('article')->field('id,content')->select();
	if($list)
	foreach($list as $key=>$vo){		
	  $data['content'] = str_replace($str,$arr['title'],$vo['content']);		
	  db('article')->where('id',$vo['id'])->update($data);
	}
}









